package com.mkh.st.common.utils;

import org.springframework.data.redis.core.ConvertingCursor;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.serializer.RedisSerializer;

import java.util.HashSet;
import java.util.Set;

/**
 * @author tsf
 * @date 2021/3/24 16:13
 * <p>
 * TODO
 */
public class CacheUtil {

	private RedisTemplate redisTemplate;


	public  CacheUtil(RedisTemplate redisTemplate)
	{
		this.redisTemplate = redisTemplate;
	}

	/**
	 * 清除缓存
	 * @param patternKey
	 */
	public void clearKey(String patternKey)
	{
		doClear(patternKey,1000l);
	}

	/**
	 * 清除缓存
	 * @param patternKey
	 * @param limit 步长
	 */
	public void clearKey(String patternKey,long limit)
	{
		doClear(patternKey,limit);
	}


	private void doClear(String patternKey,long limit)
	{
		ScanOptions scanOptions = ScanOptions.scanOptions().count(limit).match(patternKey).build();
		RedisSerializer<String> redisSerializer = (RedisSerializer<String>) redisTemplate.getKeySerializer();
		Cursor cursor = (Cursor) redisTemplate.executeWithStickyConnection(
				redisConnection -> new ConvertingCursor<>(redisConnection.scan(scanOptions), redisSerializer::deserialize));
		while (cursor!=null && cursor.hasNext())
		{
			redisTemplate.delete(cursor.next().toString());
		}

	}



}
